package dao

import (
	"context"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"mall-portalv2/global"
	"mall-portalv2/internal/model"
)

func (d *Dao) QueryOmsOrderWhereIdNoUser(ctx context.Context, id int64) (model.OmsOrder, error) {
	tb := model.OmsOrder{}
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("id = ?", id).First(&tb).Error; err != nil {
		return tb, err
	}
	return tb, nil
}

func (d *Dao) QueryOmsOrderWhereId(ctx context.Context, id int64, memberId int64) (model.OmsOrder, error) {
	tb := model.OmsOrder{}
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("id = ? AND member_id = ?", id, memberId).First(&tb).Error; err != nil {
		return tb, err
	}
	return tb, nil
}

func (d *Dao) QueryOmsOrderList(ctx context.Context, memberId int64, status, limit, offset int) ([]model.OmsOrder, error) {
	tb := model.OmsOrder{}
	result := []model.OmsOrder{}
	// 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("member_id = ? AND status = ? AND delete_status = 0", memberId, status).Limit(limit).Offset(offset).Order("id DESC").Find(&result).Error; err != nil {
		return result, err
	}
	return result, nil
}

func (d *Dao) QueryOmsOrderListCount(ctx context.Context, memberId int64, status int, MemberCom int) (int64, error) {
	tb := model.OmsOrder{}
	var (
		result int64
	)
	// 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("member_id = ? AND status = ? AND member_com = ?", memberId, status, MemberCom).Find(&tb).Count(&result).Error; err != nil {
		return result, err
	}
	return result, nil
}

func (d *Dao) QueryOmsOrderListAll(ctx context.Context, memberId int64, limit, offset int) ([]model.OmsOrder, error) {
	tb := model.OmsOrder{}
	result := []model.OmsOrder{}
	// 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("member_id = ? AND delete_status = 0", memberId).Limit(limit).Offset(offset).Order("id DESC").Find(&result).Error; err != nil {
		return result, err
	}
	return result, nil
}

func (d *Dao) QueryOmsOrderListAllNotLimit(ctx context.Context, memberId int64, MemberCom int) ([]model.OmsOrder, error) {
	tb := model.OmsOrder{}
	result := []model.OmsOrder{}
	// 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("member_id = ? AND member_com = ?", memberId, MemberCom).Find(&result).Error; err != nil {
		return result, err
	}
	return result, nil
}

func (d *Dao) QueryOmsOrderListAllNotLimitAndNoMemCom(ctx context.Context, memberId int64) ([]model.OmsOrder, error) {
	tb := model.OmsOrder{}
	result := []model.OmsOrder{}
	// 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("member_id = ?", memberId).Find(&result).Error; err != nil {
		return result, err
	}
	return result, nil
}

func (d *Dao) QueryOmsOrderListAllCount(ctx context.Context, memberId int64, MemberCom int) (int64, error) {
	tb := model.OmsOrder{}
	var (
		result int64
	)

	// 订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("member_id = ? AND member_com = ?", memberId, MemberCom).Find(&tb).Count(&result).Error; err != nil {
		return result, err
	}
	return result, nil
}

func (d *Dao) CreateOrder(ctx context.Context, insertData model.OmsOrder) (model.OmsOrder, error) {
	tb := model.OmsOrder{}
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Create(&insertData).Error; err != nil {
		return tb, err
	}
	return insertData, nil
}

func (d *Dao) UpdateOrder(ctx context.Context, ID int64, upadtes map[string]interface{}) error {
	tb := model.OmsOrder{}
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("id = ?", ID).Updates(upadtes).Error; err != nil {
		return err
	}
	return nil
}

func (d *Dao) UpdateOrderWhereOrderSn(ctx context.Context, OrderSn string, upadtes map[string]interface{}) error {
	tb := model.OmsOrder{}
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("order_sn = ?", OrderSn).Updates(upadtes).Error; err != nil {
		return err
	}
	return nil
}

func (d *Dao) UpdateOrderWhereIds(ctx context.Context, Ids []int64, upadtes map[string]interface{}, UID int64) error {
	tb := model.OmsOrder{}
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("id IN ? AND member_id = ?", Ids, UID).Updates(upadtes).Error; err != nil {
		return err
	}
	return nil
}

func (d *Dao) QueryOmsOrderWhereOrderSn(ctx context.Context, OrderSn string) (model.OmsOrder, error) {
	tb := model.OmsOrder{}
	if err := d.db.WithContext(ctx).Table(tb.TableName()).Where("order_sn = ?", OrderSn).First(&tb).Error; err != nil {
		return tb, err
	}
	return tb, nil
}

func (d *Dao) UnLockOmsOrder(ctx context.Context, orderId int64) error {
	if err := d.db.Transaction(func(tx *gorm.DB) error {

		// 查询订单下面有那些产品
		tb := model.OmsOrderItem{}
		orderItemResult := []model.OmsOrderItem{}

		if err := tx.WithContext(ctx).Table(tb.TableName()).Where("order_id = ?", orderId).Find(&orderItemResult).Error; err != nil {
			return err
		}

		for _, item := range orderItemResult {
			tb := model.ViewProductCrowdFundingDetail{}
			result := model.ViewProductCrowdFundingDetail{}

			if err := tx.WithContext(ctx).Table(tb.TableName()).Where("crowd_funding_id = ? AND crowd_funding_thali_id = ? AND product_sku_id = ? AND product_id = ?", item.PromotionId, item.PromotionSkuId, item.ProductSkuId, item.ProductId).First(&result).Error; err != nil {
				return err
			}

			global.Log.Info("查询完毕", zap.Any("data", result))

			tb2 := model.PmsSkuStock{}
			skuUpdates := make(map[string]interface{})
			skuUpdates["lock_stock"] = result.SkuLockStock - item.ProductQuantity
			if err := tx.WithContext(ctx).Table(tb2.TableName()).Where("id = ?", item.ProductSkuId).Updates(skuUpdates).Error; err != nil {
				return err
			}

			global.Log.Info("商品表库存更新")

			tb3 := model.SmsCrowdFundingThali{}
			crowdFundingUpdates := make(map[string]interface{})
			crowdFundingUpdates["lock_thali_count"] = result.CftLockThaliCount - item.ProductQuantity
			if err := tx.WithContext(ctx).Table(tb3.TableName()).Where("id = ?", item.PromotionSkuId).Updates(crowdFundingUpdates).Error; err != nil {
				return err
			}

			global.Log.Info("众筹表库存更新")

		}
		// 返回 nil 提交事务
		return nil
	}); err != nil {
		return err
	}
	return nil
}

func (d *Dao) UnLockOmsOrderFun2(ctx context.Context, ProductSkuId, SkuLockStock, CrowdFundingSkuId, CftLockThaliCount, num int64) error {
	if err := d.db.Transaction(func(tx *gorm.DB) error {

		tb2 := model.PmsSkuStock{}
		skuUpdates := make(map[string]interface{})
		skuUpdates["lock_stock"] = SkuLockStock + num
		if err := tx.WithContext(ctx).Table(tb2.TableName()).Where("id = ?", ProductSkuId).Updates(skuUpdates).Error; err != nil {
			return err
		}

		global.Log.Info("锁库存，商品表库存更新")

		tb3 := model.SmsCrowdFundingThali{}
		crowdFundingUpdates := make(map[string]interface{})
		crowdFundingUpdates["lock_thali_count"] = CftLockThaliCount + num
		if err := tx.WithContext(ctx).Table(tb3.TableName()).Where("id = ?", CrowdFundingSkuId).Updates(crowdFundingUpdates).Error; err != nil {
			return err
		}

		global.Log.Info("锁库存，众筹表库存更新")
		// 返回 nil 提交事务
		return nil
	}); err != nil {
		return err
	}
	return nil
}

func (d *Dao) LockOmsOrder(ctx context.Context, ProductSkuId, SkuLockStock, CrowdFundingSkuId, CftLockThaliCount, num int64) error {
	if err := d.db.Transaction(func(tx *gorm.DB) error {

		tb2 := model.PmsSkuStock{}
		skuUpdates := make(map[string]interface{})
		skuUpdates["lock_stock"] = SkuLockStock + num
		if err := tx.WithContext(ctx).Table(tb2.TableName()).Where("id = ?", ProductSkuId).Updates(skuUpdates).Error; err != nil {
			return err
		}

		global.Log.Info("锁库存，商品表库存更新")

		tb3 := model.SmsCrowdFundingThali{}
		crowdFundingUpdates := make(map[string]interface{})
		crowdFundingUpdates["lock_thali_count"] = CftLockThaliCount + num
		if err := tx.WithContext(ctx).Table(tb3.TableName()).Where("id = ?", CrowdFundingSkuId).Updates(crowdFundingUpdates).Error; err != nil {
			return err
		}

		global.Log.Info("锁库存，众筹表库存更新")
		// 返回 nil 提交事务
		return nil
	}); err != nil {
		return err
	}
	return nil
}
